package com.dj.controller;

import java.io.PrintWriter;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.dj.pojo.SNSUserInfo;
import com.dj.pojo.WeixinOauth2Token;
import com.dj.util.ConnectUtil;
import com.dj.util.InitUtil;
import com.dj.util.MessageUtil;
import com.dj.util.WeiXinUtil;

@Controller
public class MenuController {

	@RequestMapping("/toLogin")
	public ModelAndView toLogin(ModelAndView mv) {
		mv.setViewName("test");
		return mv;
	}
	
	@GetMapping("/getUserInfo")  
    public ModelAndView add(ModelAndView model, HttpServletRequest request, HttpServletResponse response) throws Exception {  
		SNSUserInfo snsUserInfo = null;
		try {  
        	String code = request.getParameter("code");
        	String state = request.getParameter("state");
            // 获取网页授权access_token
            WeixinOauth2Token weixinOauth2Token = WeiXinUtil.getOauth2AccessToken(WeiXinUtil.APPID, WeiXinUtil.APPSECRET, code);
            // 网页授权接口访问凭证
            String accessToken = weixinOauth2Token.getAccessToken();
            // 用户标识
            String openId = weixinOauth2Token.getOpenId();
            // 获取用户信息
            snsUserInfo = WeiXinUtil.getSNSUserInfo(accessToken, openId);
            // 设置要传递的参数
            request.setAttribute("snsUserInfo", snsUserInfo);
            request.setAttribute("state", state); 
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        model.setViewName("index");
        model.addObject("snsUserInfo", snsUserInfo);
        return model;  
	}  
	

	@GetMapping("/weixin")
	@ResponseBody
	public void toMenu(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("=============begin============");

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		String signature = request.getParameter("signature");
		String timestamp = request.getParameter("timestamp");
		String nonce = request.getParameter("nonce");
		String echostr = request.getParameter("echostr");

		response.reset();
		PrintWriter out = response.getWriter();

		if (ConnectUtil.checkSignature(signature, timestamp, nonce)) {
			// 如果校验成功，将得到的随机字符串原路返回
			System.out.println("============success=========");
			out.print(echostr);
			out.flush();
			out.close();
		}
	}

	@PostMapping("/weixin")
	@ResponseBody
	public void sendMessage(HttpServletRequest request, HttpServletResponse response) throws Exception {
		System.out.println("=============start============");
		response.reset();
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//PrintWriter out = response.getWriter();
		ServletOutputStream outputStream = response.getOutputStream();
		String message = "";
		try {
			// 将request请求，传到Message工具类的转换方法中，返回接收到的Map对象
			Map<String, String> map = MessageUtil.xmlToMap(request);

			// 从集合中，获取XML各个节点的内容
			String ToUserName = map.get("ToUserName");
			String FromUserName = map.get("FromUserName");
			//String CreateTime = map.get("CreateTime");
			String MsgType = map.get("MsgType");
			String Content = map.get("Content");
			//String MsgId = map.get("MsgId");

			if (MsgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {// 判断消息类型是否是文本消息(text)
				if (Content.equals("1")) {
					message = InitUtil.initText(ToUserName, FromUserName, "帅哥Jon");
				} else if (Content.equals("2")) {
					message = InitUtil.initText(ToUserName, FromUserName, "美女Min");
				} else if (Content.equals("3")) {
					message = InitUtil.initNewsMessage(ToUserName, FromUserName);
				} else if (Content.equals("4")) {
					message = InitUtil.initImageMessage(ToUserName, FromUserName);
				}else if (Content.equals("?") || Content.equals("？")) {
					message = InitUtil.initText(ToUserName, FromUserName, InitUtil.menuText());
				} else {
					message = InitUtil.initText(ToUserName, FromUserName, "没让你选的就别瞎选!");
				}
			} else if (MsgType.equals(MessageUtil.REQ_MESSAGE_TYPE_EVENT)) {// 判断是否为事件类型
				// 从集合中，或许是哪一种事件传入
				String eventType = map.get("Event");
				if (eventType.equals(MessageUtil.EVENT_TYPE_SUBSCRIBE)) {// 关注事件
					message = InitUtil.initText(ToUserName, FromUserName, InitUtil.menuText());
				} else if (eventType.equals(MessageUtil.EVENT_TYPE_CLICK)) {//点击事件
					String eventKey = map.get("EventKey");
					message = InitUtil.initEvnet(ToUserName, FromUserName, eventKey);
				}
			}
			System.out.println(message);
			outputStream.write(message.getBytes("UTF-8"));
			//out.print(message); // 返回转换后的XML字符串
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			outputStream.flush();
			outputStream.close();
			/*out.flush();
			out.close();*/
		}
		System.out.println("=============end============");
	}
}
